<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTools>
        <template v-slot:left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>

        <template #right>
          <el-button
            type="danger"
            size="small"
            @click="$router.push('/import?type=user')"
          >excel导入员工</el-button>
          <el-button
            type="success"
            size="small"
            @click="handleDownload"
          >excel导出员工</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <!-- 员工table -->
      <el-card style="margin-top: 10px">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="图片" prop="staffphoto">
            <template v-slot="{ row }">
              <img
                v-errorimg="defaultImage"
                :src="row.staffPhoto || defaultImage"
                class="boderimg"
                @click="clickShowCodeDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatEmployment"
            sortable=""
          />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{ row }">
              {{ formatEntry(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                :disabled="!checkPermission('POINT-USER-UPDATE')"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="assignRole(row.id)"
              >角色</el-button>
              <el-button
                :disabled="!checkPermission('POINT-USER-DELETE')"
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增员工组件 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <!-- 分享展示, 预览的二维码的弹层 -->
    <el-dialog width="300px" title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- :user-id="userId" -->
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employee'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import dayjs from 'dayjs'
import defaultImage from '@/assets/common/head.jpg'
import AssignRole from './components/assign-role'
import QrCode from 'qrcode'
export default {
  name: 'Employees',

  components: {
    AddEmployee,
    AssignRole
  },

  data() {
    return {
      page: 1,
      size: 10,
      total: 0,
      employeeList: [],
      showCodeDialog: false,
      showRoleDialog: false,
      showDialog: false,
      defaultImage,
      userId: ''
    }
  },

  created() {
    this.getEmployeeList()
  },

  methods: {
    async getEmployeeList() {
      const {
        data: { rows, total }
      } = await reqGetEmployeeList(this.page, this.size)
      this.employeeList = rows
      this.total = total
    },

    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },

    formatEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      //  1:正式   2.非正式
      // return cellValue === 1 ? '正式' : '非正式'

      const obj = EmployeeEnum.hireType.find((item) => item.id === +cellValue)

      return obj ? obj.value : '未知'
    },

    formatEntry(time) {
      // 借助第三方的包dayjs或moment.js
      // return time
      return dayjs(time).format('YYYY年MM月DD')
    },
    async delEmployee(id) {
      const res = await this.$confirm('确定要删除该员工?', '温馨提示').catch(error => error)
      if (res === 'chacel') return
      await reqDelEmployee(id)
      this.$message.success('删除成功')
      this.getEmployeeList()
    },
    // excel导出功能
    async handleDownload() {
      // 员工的头部信息
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      // 获取所有的员工数据信息
      const {
        data: { rows }
      } = await reqGetEmployeeList(1, this.total)
      // console.log(rows)

      // 已有的数据: [{id:xxx,mobile:xxx,username:xxxx,..,,,},{},...]   16个{}
      // 要的数据: [['管理员','13812345678'],[],....]   16个[]

      const arr = [] // 外层的[]

      rows.forEach((item) => {
        const newArr = []
        headersArr.forEach((v) => {
          const enkey = headersRelations[v]
          if (enkey === 'formOfEmployment') {
            // item[enkey] // ===  1  => 正式
            const obj = EmployeeEnum.hireType.find(
              (value) => value.id === +item[enkey]
            )
            const res = obj ? obj.value : '未知'
            newArr.push(res)
          } else {
            newArr.push(item[enkey])
          }
        })
        arr.push(newArr)
      })

      // console.log(arr)

      // 按需加载资源
      import('@/vendor/Export2Excel').then((excel) => {
        // console.log(excel)
        // header: 表头
        // data: 数据
        // filename: 导出的文件名称
        // autoWidth: 自动适配宽度
        // bookType:文件的扩展名
        excel.export_json_to_excel({
          multiHeader,
          merges,
          header: headersArr,
          data: arr,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    clickShowCodeDialog(data) {
      if (data === '') return
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, data)
      })
    },
    // 显示员工的角色
    assignRole(userId) {
      this.userId = userId
      this.showRoleDialog = true
    },
    checkPermission(key) {
      if (this.$store.getters.roles) {
        return this.$store.getters.roles.points.includes(key)
      } else {
        return false
      }
    }
  }
}
</script>

<style scoped lang="scss">
.boderimg {
  width: 70px;
  height: 70px;
  border-radius: 50%;
}
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
